package com.hnchances.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.hnchances.config.JwtConfig;
import com.hnchances.entity.Class;
import com.hnchances.entity.Course;
import com.hnchances.entity.Student;
import com.hnchances.entity.User;
import com.hnchances.mapper.UserMapper;
import com.hnchances.service.ClassService;
import com.hnchances.service.CourseService;
import com.hnchances.service.StudentService;
import com.hnchances.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnchances.utils.AliYunSmsUtils;
import com.hnchances.utils.IpUtil;
import com.hnchances.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.net.SocketException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hnchances.utils.AliYunSmsUtils.getNewcode;
import static com.hnchances.utils.AliYunSmsUtils.sendSms;

/**
 * <p>
 *  服务实现类
 * </p>
 *

 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StudentService studentService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CourseService courseService;
    @Resource
    private ClassService classService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private JwtConfig jwtConfig;

    @Override
    public Result register(User user) {
        User dbUser = userMapper.findByUserName(user.getUsername());
        if (dbUser!=null){
            return Result.error().message("系统中已存在此账号");
        }
        //学生注册
        if (user.getIdentity().equals(0)){
            //查找数据库中存不存在对应身份证信息的学生
            Student dbStudent = studentService.findStudentByIdCard(user.getIdcard());
            if (dbStudent!=null){
                //密码MD5加密
                user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
                user.setStudentid(dbStudent.getId());
                user.setClassid(dbStudent.getClassid());
                user.setCreatdatetime(new Date());
                user.setUpdatedatetime(new Date());
                user.setStatus(0);
                user.setVerify(1);
                try {
                    //获取ip
                    String ip= IpUtil.getLocalIp4Address().get().toString().replaceAll("/","");
                    user.setLoginip(ip);
                } catch (SocketException e) {
                    e.printStackTrace();
                }
                baseMapper.insert(user);
                return Result.ok().message("注册成功");
            }else {
                return Result.error().message("注册失败，系统里不存在您的信息");
            }
        }
        //老师注册
        else if (user.getIdentity().equals(1)){
            String redisCode = redisTemplate.opsForValue().get(user.getPhone());
            if (redisCode!=null){
                if (user.getCode().equals(redisCode)) {
                    //判断系统中是否存在课程和班级
                    Course dbCourse = courseService.getById(user.getCourseid());
                    Class dbClass = classService.getById(user.getClassid());
                    if (dbClass == null || dbCourse == null) {
                        return Result.error().message("系统中不存在该班级信息或课程信息");
                    }
                    //密码MD5加密
                    user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
                    user.setCreatdatetime(new Date());
                    user.setUpdatedatetime(new Date());
                    user.setStatus(0);
                    user.setVerify(1);
                    try {
                        //获取ip
                        String ip = IpUtil.getLocalIp4Address().get().toString().replaceAll("/", "");
                        user.setLoginip(ip);
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }
                    baseMapper.insert(user);
                    return Result.ok().message("注册成功");
                }else {
                    return Result.error().message("验证码有误");
                }
            }else {
                return Result.error().message("验证码已过期");
            }
        }
        return Result.error().message("系统中不存在该身份");
    }

    @Override
    public Result getCode(String phone) {
        AliYunSmsUtils.setNewcode();
        String code = Integer.toString(getNewcode());
        System.out.println("发送的验证码为："+code);
        //发短信
        try {
            SendSmsResponse response =sendSms(phone,code);
            System.out.println("Code=" + response.getCode());
            System.out.println("Message=" + response.getMessage());
            System.out.println("RequestId=" + response.getRequestId());
            System.out.println("BizId=" + response.getBizId());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        //存入redis
        redisTemplate.opsForValue().set(phone,code);
        redisTemplate.expire(phone,3000, TimeUnit.SECONDS);
        return Result.ok().message("发送成功").data("code",code);
    }

    @Override
    public Result login(User user) {
        List<User> userList = baseMapper.selectList(null);
        for (User thisUser : userList) {
            if (thisUser.getUsername().equals(user.getUsername()) &&DigestUtils.md5DigestAsHex(user.getPassword().getBytes()).equals(thisUser.getPassword())){
                String token = jwtConfig.createToken(thisUser.getId().toString());
                return Result.ok().message("登陆成功").data("token",token);

            }
        }
        return Result.error().message("登录失败，用户名或密码有误。");
    }

    @Override
    public Result update(User user) {
        int i = baseMapper.updateById(user);
        if (i==1){
            return Result.ok().message("修改成功");
        }
        return Result.error().message("修改失败，服务器存在异常");
    }

    @Override
    public Result delete(String id) {
        User dbUser = baseMapper.selectById(id);
        dbUser.setStatus(1);
        int i = baseMapper.updateById(dbUser);
        if (i==1){
            return Result.ok().message("删除成功");
        }
        return Result.error().message("删除失败，服务器存在异常");
    }
}
